﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace AnthStat.WPF.Presentation.Controls
{
    public sealed class NumericTextBox : TextBox
    {
        protected override void OnPreviewTextInput(TextCompositionEventArgs e)
        {
            base.OnPreviewTextInput(e);

            var culture = System.Threading.Thread.CurrentThread.CurrentUICulture;

            if (e.Text != culture.NumberFormat.NumberDecimalSeparator)
            {
                double result;
                var success = Double.TryParse(e.Text, NumberStyles.Any, culture, out result);

                if (!success)
                {
                    e.Handled = true;
                }
            }
            else if (e.Text.Equals(culture.NumberFormat.NumberDecimalSeparator) &&
                     Text.Contains((culture.NumberFormat.NumberDecimalSeparator)))
            {
                e.Handled = true;
            }
        }
    }
}
